package demo.example.controller;

import demo.example.common.ApiRestResponse;
import demo.example.common.Constant;
import demo.example.exception.TTException;
import demo.example.exception.TTExceptionEnum;
import demo.example.model.pojo.User;
import demo.example.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;

/**
 * @Date 2022/7/13 19:33
 * @Created by wangle
 * @Description
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    UserService userService;

    /**
     * 测试
     * @return
     */
    @GetMapping("/test")
    public User test(){

        return userService.getUser();

    }

    /**
     * 登录
     */
    @PostMapping("/login")
    public ApiRestResponse login(@RequestBody User user,
                                 HttpSession session)
            throws TTException {

        //校验用户名密码不为空
        if (StringUtils.isEmpty(user.getUsername())) {

            return ApiRestResponse.error(TTExceptionEnum.NEED_USER_NAME);
        }
        if (StringUtils.isEmpty(user.getPassword())) {
            return ApiRestResponse.error(TTExceptionEnum.NEED_PASSWORD);
        }
        User userselect = userService.login(user.getUsername(), user.getPassword());

        //保存用户信息时，不保存密码
        userselect.setPassword(null);
        session.setAttribute(Constant.TT_USER, userselect);
        return ApiRestResponse.success(userselect);

    }
    /**
     * 登出，清除session
     */
    @PostMapping("/logout")
    @ResponseBody
    public ApiRestResponse logout(HttpSession session) {
        session.removeAttribute(Constant.TT_USER);

        return ApiRestResponse.success();
    }

    @PostMapping("/register")
    @ResponseBody
    public ApiRestResponse register(@RequestBody User user) {
        if(StringUtils.isEmpty(user.getUsername())) {
            return ApiRestResponse.error(TTExceptionEnum.NEED_USER_NAME);
        }
        if(StringUtils.isEmpty(user.getPassword())) {
            return ApiRestResponse.error(TTExceptionEnum.NEED_PASSWORD);
        }
        //密码长度不能少于8位
        if(user.getPassword().length() < 8) {
            return ApiRestResponse.error(TTExceptionEnum.PASSWORD_TOO_SHORT);
        }

        userService.register(user.getUsername(), user.getPassword());
        return ApiRestResponse.success();
    }

}
